package com.coocaa.aries.core.tool.upload.util;

import com.coocaa.aries.core.tool.InstanceUtil;
import com.coocaa.aries.core.tool.file.FileAnalyzerUtil;
import com.coocaa.aries.core.tool.file.FileMd5Util;
import com.coocaa.aries.core.tool.random.RandomUtil;
import com.coocaa.aries.core.tool.upload.model.UploadConfig;
import com.coocaa.aries.core.tool.upload.model.UploadResult;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @author : bijiahao
 * @date : 2019/4/9.
 * @description:
 */
public class UploadUtil {

    public static List<UploadResult> uploadTempFile(HttpServletRequest request, UploadConfig uploadConfig) {
        // 将 request 转化为 multipartRequest
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        // 从 multipartRequest 获取 fileMap
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        List<UploadResult> uploadResultList = InstanceUtil.newArrayList();
        for (Map.Entry<String, MultipartFile> entry : fileMap.entrySet()) {
            // 获取 multipartFile
            MultipartFile multipartFile = entry.getValue();
            //处理文件上传
            UploadResult uploadResult = getUploadResult(multipartFile, uploadConfig);
            uploadResultList.add(uploadResult);
        }
        return uploadResultList;
    }


    private static UploadResult getUploadResult(MultipartFile multipartFile, UploadConfig uploadConfig) {
        String fileOriginName = multipartFile.getOriginalFilename();
        String extName = FileAnalyzerUtil.getFileExtName(fileOriginName);
        //校验类型
        validExtName(extName, uploadConfig.getTypesLimit());
        String newName = getNewFileName(extName);
        String tempSavePath = getTempUploadPath(uploadConfig.getUploadDir(), newName);
        File tempSaveFile = new File(tempSavePath);
        handleMakeDirs(tempSaveFile);
        try {
            multipartFile.transferTo(tempSaveFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String fileMd5 = FileMd5Util.getFileMD5(tempSavePath);
        UploadResult uploadResult = new UploadResult();
        uploadResult.setFileMd5(fileMd5);
        uploadResult.setNewFileName(newName);
        uploadResult.setOriginFileName(FileAnalyzerUtil.getFileNameTrimSuffix(fileOriginName));
        uploadResult.setFileType(extName);
        uploadResult.setFileSize(String.valueOf(multipartFile.getSize()));
        uploadResult.setTempStorePath(tempSavePath);
        return uploadResult;
    }

    private static void validExtName(String extName, String typesLimit) {
        if (StringUtils.isNotBlank(typesLimit) && !typesLimit.contains(extName.toLowerCase())) {
            throw new RuntimeException("只能上传" + typesLimit + "文件");
        }
    }


    /**
     * 获取新的文件名称
     *
     * @param extName
     * @return
     */
    private static String getNewFileName(String extName) {
        StringBuilder pathDir = new StringBuilder();
        pathDir.append(RandomUtil.getRandomStoreDir())
                .append(extName);
        return pathDir.toString();
    }


    /**
     * 获取临时上传路径
     *
     * @param uploadDir
     * @param newName
     * @return
     */
    private static String getTempUploadPath(String uploadDir, String newName) {
        StringBuilder path = new StringBuilder();
        path.append(uploadDir)
                .append("/")
                .append(newName);
        return path.toString();

    }

    /**
     * 处理创建目录
     *
     * @param tempSaveFile
     */
    private static void handleMakeDirs(File tempSaveFile) {
        if (!tempSaveFile.getParentFile().exists()) {
            try {
                FileUtils.forceMkdir(tempSaveFile.getParentFile());
            } catch (IOException e) {
                throw new RuntimeException("请检查！");
            }
        }
    }


}
